package com.situ.shoplook.admin.api;

import com.situ.shoplook.common.model.Category;
import com.situ.shoplook.common.service.CategoryService;
import com.situ.shoplook.common.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * <p>
 * created by 千堆雪 on 2024/8/24, last modified by 千堆雪 on 2024/8/24
 */
@RestController
@RequestMapping(value = "/api/v1/categories", produces = "application/json;charset=utf-8")
public class CategoryApi {
    private CategoryService categoryService;

    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 查询所有商品类别
     *
     * @return 响应json
     */
    @GetMapping
    public JsonResult<List<Category>> findAll() {
        List<Category> categories = this.categoryService.findAll();
        return JsonResult.success(categories);
    }

    /**
     * 查询商品类别树
     *
     * @return 类别树的根节点
     */
    @GetMapping("/tree")
    public JsonResult<Category> findCategoryTree() {
        Category root = this.categoryService.findTree();
        return JsonResult.success(root);
    }

    @GetMapping({"/id/{p1}", "/id/", "/id"})
    public JsonResult<Category> findById(@PathVariable(required = false) Integer p1, Integer id) {
        if (p1 == null) {
            p1 = id;
        }
        Category category = this.categoryService.findById(p1);
        return JsonResult.success(category);
    }

    @PostMapping
    public JsonResult<String> save(@RequestBody Category category) {
        boolean b = this.categoryService.save(category);
        return JsonResult.of(b, b ? "操作成功" : "操作失败");
    }

    @PutMapping
    public JsonResult<String> update(@RequestBody Category category) {
        boolean b = this.categoryService.update(category);
        return JsonResult.of(b, b ? "操作成功" : "操作失败");
    }

    //批量删除
    @DeleteMapping
    public JsonResult<?> deleteByIds(@RequestBody Integer[] ids) {
        int rows = 0;//不级联删除
        try {
            rows = this.categoryService.deleteByIds(ids, false);
            return JsonResult.of(rows > 0, Map.of("rows", rows, "msg", rows > 0 ? "操作成功，共删除" + rows + "行" : "操作失败"));
        } catch (Exception e) {
            return JsonResult.fail("操作失效，请检查要删除的类别是否包含子类别");
        }
    }
}
